import 'package:BeeApp/MainPage/MainToolPage.dart';
import 'package:BeeApp/MainPage/http_request.dart';
import 'package:BeeApp/ShopPage/UserLocationModelPage.dart';
import 'package:BeeApp/ShopPage/UserLocationPage.dart';
import 'package:BeeApp/ShopPage/UserLocationSearchPage.dart';
import 'package:amap_search_fluttify/amap_search_fluttify.dart';
import 'package:flutter/material.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

// ignore: must_be_immutable
class UserAddLocationPage extends StatefulWidget {
  final bool isSend;
  UserAddLocationPage(this.isSend, {Key key}) : super(key: key);

  @override
  _MainUserPageState createState() => _MainUserPageState();
}

class _MainUserPageState extends State<UserAddLocationPage> {
  final addressText = TextEditingController();
  final nameText = TextEditingController();
  final mobileText = TextEditingController();
  String shengStr = "";
  String shiStr = "";
  String quStr = "";
  String zhenStr = "";
  String addressStr = "";
  String titleStr = "";
  String latStr = "";
  String longStr = "";

  TabController _controller;
  List tabs = ["常用地址", "历史地址"];
  List pages;
  int selectPage = 0;
  double viewH =
      screenHeight - appBarHeight - bottomBarHeight - statusBarHeight;
  RefreshController _refreshController =
      RefreshController(initialRefresh: false);

  @override
  void initState() {
    super.initState();
    print(widget.isSend);

    pages = [
      UserLocationPage(
        widget.isSend,
        "2",
        refreshController: _refreshController,
        chooseV: (LocationModel model) {
          print(model.address);
          Navigator.pop(context, model);
        },
      ),
      UserLocationPage(
        widget.isSend,
        "1",
        refreshController: _refreshController,
        chooseV: (LocationModel model) {
          print(model.address);
          Navigator.pop(context, model);
        },
      ),
    ];
    _controller = TabController(
      length: pages.length,
      vsync: ScrollableState(),
    );
  }

  @override
  void dispose() {
    super.dispose();
    _controller?.removeListener(() {});
    _controller?.dispose();
  }

  Text labelText01(String string) {
    return Text(
      string,
      style: TextStyle(
        color: Color(0xFF333333),
        fontSize: setFontSize(32),
      ),
    );
  }

  Widget lineView01() {
    return Container(
      height: 10,
      color: Color(0xFFF5F5F5),
    );
  }

  Widget lineView02() {
    return Container(
      height: 1,
      color: Color(0xFFEDEDED),
    );
  }

  TextStyle textStyle01(int index) {
    if (index == selectPage) {
      return TextStyle(
        color: Color(0xFF333333),
        fontSize: setFontSize(36),
      );
    } else {
      return TextStyle(
        color: Color(0xFFCBCBCB),
        fontSize: setFontSize(34),
      );
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: getAppBar(context, "地址信息"),
      body: GestureDetector(
        behavior: HitTestBehavior.translucent,
        onTap: () {
          FocusScope.of(context).requestFocus(FocusNode());
        },
        child: Container(
          height: viewH,
          child: ListView(
            children: <Widget>[
              lineView01(),
              addressView(),
              lineView01(),
              Container(
                height: setHeight(80),
                child: TabBar(
                  controller: _controller,
                  labelColor: Color(0xFF333333),
                  labelStyle: TextStyle(fontSize: setFontSize(30)),
                  labelPadding: EdgeInsets.fromLTRB(0, 0, 0, 2),
                  unselectedLabelColor: Color(0xFF666666),
                  indicatorColor: Color(0xFFFF9D11),
                  indicatorWeight: 2,
                  indicatorSize: TabBarIndicatorSize.label,
                  onTap: (value) {
                    setState(() {
                      selectPage = value;
                    });
                  },
                  tabs: tabs.map((e) => Tab(text: e)).toList(),
                ),
              ),
              Container(
                height: viewH - setHeight(740),
                child: TabBarView(
                  controller: _controller,
                  children: pages.map((e) => Tab(child: e)).toList(),
                ),
              ),
              changeView()
            ],
          ),
        ),
      ),
    );
  }

  Widget addressView() {
    return Container(
      height: setHeight(440),
      padding: EdgeInsets.all(10),
      child: Column(
        children: <Widget>[
          SizedBox(height: setHeight(10)),
          InkWell(
            child: Container(
              // height: setHeight(60),
              child: Row(
                children: <Widget>[
                  labelText01("地址："),
                  Expanded(
                    child: Container(
                      child: shiStr.length == 0
                          ? Text(
                              widget.isSend ? "请填写发货人地址" : "请填写收货人地址",
                              style: TextStyle(
                                color: Color(0xFFAEAEAE),
                                fontSize: setFontSize(30),
                              ),
                            )
                          : labelText01(shengStr + shiStr + quStr),
                    ),
                  ),
                  Image.asset(
                    "images/MainLocationImage.png",
                    height: setHeight(50),
                  ),
                ],
              ),
            ),
            onTap: () {
              print("object");
              Navigator.push(
                context,
                MaterialPageRoute(
                    builder: (context) => UserLocationSearchPage()),
              ).then((value) {
                if (value != null) {
                  Poi poi = value;
                  // changeAddress(poi);
                  if (mounted) {
                    setState(() {
                      shengStr = poi.provinceName; //省
                      shiStr = poi.cityName; // 市
                      quStr = poi.adName; // 区 县
                      zhenStr = poi.address; // 街道  镇
                      titleStr = poi.title; //地址名称
                      latStr = poi.latLng.latitude.toString();
                      longStr = poi.latLng.longitude.toString();
                      addressStr = shengStr + shiStr + quStr;
                      // addressText.text = poi.address + titleStr;
                    });
                  }
                }
                print(value);
              });
            },
          ),
          SizedBox(height: 20),
          lineView02(),
          SizedBox(height: 10),
          Container(
            height: setHeight(100),
            child: Row(
              children: <Widget>[
                labelText01("楼号及门牌号："),
                Expanded(
                  child: TextField(
                    controller: addressText,
                    textAlign: TextAlign.start,
                    cursorColor: Colors.grey, //设置光标
                    decoration: InputDecoration(
                      contentPadding: const EdgeInsets.symmetric(
                          vertical: 1.0, horizontal: 1.0),
                      hintText: '请输入楼号及门牌号',
                      hintStyle:
                          TextStyle(fontSize: 14, color: Color(0xFFAEAEAE)),
                      border: OutlineInputBorder(
                          borderRadius: BorderRadius.circular(15),
                          borderSide: BorderSide.none),
                      fillColor: Color(0xFFF2F2F2),
                    ),
                    style: TextStyle(fontSize: 14, color: Color(0xFF333333)),
                    onChanged: (value) async {},
                  ),
                ),
              ],
            ),
          ),
          SizedBox(height: 10),
          lineView02(),
          SizedBox(height: 10),
          Container(
            child: Row(
              children: <Widget>[
                Container(
                  width: 160,
                  child: Row(
                    children: <Widget>[
                      labelText01("姓名："),
                      Expanded(
                          child: TextField(
                        controller: nameText,
                        textAlign: TextAlign.start,
                        cursorColor: Colors.grey[400], //设置光标
                        decoration: InputDecoration(
                          border: InputBorder.none,
                          hintText: "姓名（可不填）",
                          hintStyle: TextStyle(
                            fontSize: setFontSize(32),
                            color: Color(0xFFAEAEAE),
                          ),
                        ),
                        style: TextStyle(
                          fontSize: setFontSize(32),
                          color: Color(0xFF333333),
                        ),
                      )),
                    ],
                  ),
                ),
                Expanded(
                  child: Row(
                    children: <Widget>[
                      labelText01("电话："),
                      Expanded(
                          child: TextField(
                        controller: mobileText,
                        keyboardType: TextInputType.number,
                        textAlign: TextAlign.start,
                        cursorColor: Colors.grey[400], //设置光标
                        decoration: InputDecoration(
                          border: InputBorder.none,
                          hintText: "请输入手机号",
                          hintStyle: TextStyle(
                            fontSize: setFontSize(32),
                            color: Color(0xFFAEAEAE),
                          ),
                        ),
                        style: TextStyle(
                          fontSize: setFontSize(32),
                          color: Color(0xFF333333),
                        ),
                      )),
                      InkWell(
                        child: Image.asset(
                          "images/OtherUserImage.png",
                          height: setHeight(50),
                        ),
                        onTap: () async {
                   /*       ContactPicker _contactPicker = ContactPicker();
                          Contact myContact =
                              await _contactPicker.selectContact();
                          if (myContact != null) {
                            if (mounted) {
                              setState(() {
                                nameText.text = myContact.fullName.toString();
                                mobileText.text = myContact.phoneNumber.number
                                    .toString()
                                    .replaceAll(RegExp(r"\s+\b|\b\s"), "");
                              });
                            }
                          }*/
                        },
                      ),
                    ],
                  ),
                ),
              ],
            ),
          )
        ],
      ),
    );
  }

  void changeAddress(Poi poi) async {
    final reGeocodeList = await AmapSearch.instance.searchReGeocode(
      poi.latLng,
      radius: 200.0,
    );

    if (mounted) {
      setState(() {
        shengStr = reGeocodeList.provinceName; //省
        shiStr = reGeocodeList.cityName; // 市
        quStr = reGeocodeList.districtName; // 区 县
        zhenStr = reGeocodeList.township; // 街道  镇
        titleStr = poi.title; //地址名称
        latStr = poi.latLng.latitude.toString();
        longStr = poi.latLng.longitude.toString();

        addressStr = shengStr + shiStr + quStr + zhenStr;
        addressText.text = poi.address + titleStr;
      });
      print(reGeocodeList);
      print(reGeocodeList.provinceName);
      print(reGeocodeList.cityName);
      print(reGeocodeList.districtName);
      print(reGeocodeList.township);
      print(reGeocodeList.cityName);
    }
  }

  Widget changeView() {
    return InkWell(
      child: Container(
        padding: EdgeInsets.all(setWidth(30)),
        child: Container(
          height: 50,
          alignment: Alignment.center,
          decoration: BoxDecoration(
              color: Color(0xFFFF8629),
              borderRadius: BorderRadius.all(Radius.circular(12.0)),
              border: Border.all(color: Color(0xFF333333), width: setWidth(3))),
          child: Text(
            "确定",
            style: TextStyle(
              color: Color(0xFF222222),
              fontSize: setFontSize(34),
              fontWeight: FontWeight.w600,
            ),
          ),
        ),
      ),
      onTap: () {
        print("object");
        addAddress();
      },
    );
  }

  void addAddress() {
    if (shengStr.length == 0 || shiStr.length == 0 || quStr.length == 0) {
      showToast("请选择地址");
      return;
    }
    if (addressText.text.length == 0) {
      showToast("请输入门牌号");
      return;
    }
    if (nameText.text.length == 0) {
      showToast("请输入姓名");
      return;
    }
    if (!isPhone(mobileText.text)) {
      showToast("请输入正确的手机号");
      return;
    }
    Map<String, dynamic> dic = Map();
    dic["token"] = getData("token");
    dic["province"] = shengStr;
    dic["city"] = shiStr;
    dic["area"] = quStr;
    dic["town"] = zhenStr;
    dic["address"] = shengStr + shiStr + quStr;
    dic["building_number"] = addressText.text;
    dic["title"] = titleStr;
    dic["realname"] = nameText.text;
    dic["mobile"] = mobileText.text;
    dic["lat"] = latStr;
    dic["lng"] = longStr;
    showLoading(context);
    DioUtils.postHttp(
      context,
      widget.isSend
          ? "goodsuser/add_send_address"
          : "goodsuser/add_recive_address",
      parameters: dic,
      onSuccess: (t) {
        dismissLoading(context);
        showToast(t["msg"].toString());
        dic["id"] = widget.isSend
            ? t["data"]["send_address_id"].toString()
            : t["data"]["recive_address_id"].toString();
        LocationModel model = LocationModel.fromJson(dic);
        Navigator.pop(context, model);
      },
      onError: (error) {
        dismissLoading(context);
        print(error);
      },
    );
  }
}
